package com.shoponline.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;
import com.shoponline.dao.DAOFactory;
import com.shoponline.dao.UserDAOTest;
import com.shoponline.po.User;
import com.shoponline.service.LoginService;

public class LoginAction extends ActionSupport{

	
	private LoginService loginService;
	private String email;
	private String password;
	
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	
	public LoginService getLoginService() {
		return loginService;
	}
	public void setLoginService(LoginService loginService) {
		this.loginService = loginService;
	}
	
	
	public void login() throws IOException{
		
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		HttpSession session = request.getSession();
		response.setContentType("text/html;charset=utf-8");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		try{
			
			User user = loginService.CheckLogin(this.getEmail(), this.getPassword());
			String ststus = "true";
			String result="";
			if(user!=null){
			
				session.setAttribute("loginer", user);
				System.out.println("session.save(loginer):"+user);
				ststus="true";
				result = "<user status='"+ststus+"'>" +
						"<username>"+user.getUsername()+"</username>" +
						"<useremail>"+user.getEmail()+"</useremail>" +
				"</user>";
				
			}else{
				
				ststus="false";
				result = "<user status='"+ststus+"'>" +
						"<username></username>" +
						"<useremail></useremail>" +
				"</user>";
			}
			
			out.print(result);
			out.flush();
			out.close();
			
		}catch(Exception e){
			
			e.printStackTrace();
		}
		
	}
	
	public void logout() throws IOException{
		
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		HttpSession session = request.getSession();
		response.setContentType("text/html;charset=utf-8");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		Enumeration<String> e = request.getSession().getAttributeNames();
		
		if(e.hasMoreElements()){
			
			String   sessionName   =   (String)e.nextElement();
			session.removeAttribute(sessionName); 
			System.out.println("session.remove("+sessionName+")");
			out.print("success");
			
		}
		
	}
	
	
	
}
